package io;

import com.alibaba.fastjson.JSON;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;

/**
 * @author 26029
 * @date 2025/4/17
 * @description
 */
public class LearnOtherBinarySerialize {
    public static void main(String[] args) throws IOException {
        Car car = new Car("小米su7", 250000);

        System.out.println("------------Hessian------------");
        System.out.println("Hessian支持多种语言，可移植，是二进制序列化，性能比JDK和JSON序列化快");
        String hessianFilePath = "D:/project/learnJava/src/main/java/io/hessian.bin";
        HessianOutput out = new HessianOutput(new FileOutputStream(hessianFilePath));
        out.writeObject(car);
        HessianInput in = new HessianInput(new FileInputStream(hessianFilePath));
        Car hessianObj = (Car) in.readObject();
        System.out.println("Hessian: " + hessianObj);

        System.out.println("------------Kryo------------");
        System.out.println("Kryo是用于 Java 的快速高效的二进制对象图序列化框架，不能移植到java外，速度快体积小");
        String kryoFilePath = "D:/project/learnJava/src/main/java/io/kryo.bin";
        Kryo kryo = new Kryo();
        kryo.register(Car.class);
        Output output = new Output(new FileOutputStream(kryoFilePath));
        kryo.writeObject(output, car);
        output.close();
        Input input = new Input(new FileInputStream(kryoFilePath));
        Car kryoObj = kryo.readObject(input, Car.class);
        input.close();
        System.out.println("Kryo: " + kryoObj);

        System.out.println("------------fastjson------------");
        System.out.println("alibaba开发的高性能json-Java处理库");
        System.out.println("fastjson默认不会使用反射访问私有字段，需要字段有getter/setter方法");
        String fastjson = JSON.toJSONString(car);
        System.out.println("fastjson序列化后：" + fastjson);
        Car fastjsonObj = JSON.parseObject(fastjson, Car.class);
        System.out.println("fastjson反序列化后：" + fastjsonObj);

        System.out.println("------------jackson------------");
        System.out.println("应用最广泛的最成熟的开源的json处理库");
        ObjectMapper objectMapper = new ObjectMapper();
        String jackson = objectMapper.writeValueAsString(car);
        System.out.println("jackson序列化后：" + jackson);
        Car jacksonObj = objectMapper.readValue(jackson, Car.class);
        System.out.println("jackson反序列化后：" + jacksonObj);
    }
}

